package com.eshop.modules.customer.rest;

import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ResponseBody;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import com.eshop.utils.RedisUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import com.eshop.annotation.AnonymousAccess;
import me.chanjar.weixin.mp.api.WxMpService;
import com.eshop.utils.RecodeUtil;
import java.net.URLEncoder;
import com.eshop.modules.mp.config.WxMpConfiguration;
import com.eshop.exception.BadRequestException;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import com.eshop.utils.RedisUtils;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import io.swagger.annotations.Api;

@Api(tags = { "微信" })
@Controller
@RequestMapping({ "/api/wxmp" })
public class QrCodeController
{
    private static final Logger log;
    private final RedisUtils redisUtils;
    
    @AnonymousAccess
    @GetMapping({ "/qrcode" })
    public void qrcode(final HttpServletRequest request, final HttpServletResponse response, @RequestParam("key") final String key) {
        final String adminApiUrl = this.redisUtils.getY("admin_api_url");
        if (StrUtil.isBlank((CharSequence)adminApiUrl)) {
            throw new BadRequestException("请配置后台-->商城配置-->商城系统配置-->后台Api地址");
        }
        final WxMpService wxService = WxMpConfiguration.getWxMpService();
        if (wxService == null) {
            throw new IllegalArgumentException("未找到对应配置的服务，请核实！");
        }
        final String state = key;
        final String url = adminApiUrl + "/api/wxmp/userInfo";
        final String redirectURL = wxService.getOAuth2Service().buildAuthorizationUrl(url, "snsapi_userinfo", URLEncoder.encode(state));
        QrCodeController.log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        RecodeUtil.creatRrCode(redirectURL, 180, 180, response);
    }
    
    @AnonymousAccess
    @GetMapping({ "/wechatCode" })
    public ResponseEntity wechatCode() {
        final String wechatFollowImg = this.redisUtils.getY("wechat_follow_img");
        if (StrUtil.isBlank((CharSequence)wechatFollowImg)) {
            throw new BadRequestException("请配置后台-->微信管理-->公众号配置->关注二维码");
        }
        return ResponseEntity.ok(wechatFollowImg);
    }
    
    @AnonymousAccess
    @ResponseBody
    @GetMapping({ "/userInfo" })
    public void userInfo(final HttpServletRequest request, @RequestParam("code") final String code, @RequestParam("state") final String key) throws Exception {
        QrCodeController.log.info("【微信网页授权】code={}", code);
        QrCodeController.log.info("【微信网页授权】state={}", key);
        final WxMpService wxService = WxMpConfiguration.getWxMpService();
        if (wxService == null) {
            throw new IllegalArgumentException("未找到对应配置的服务，请核实！");
        }
        try {
            final WxOAuth2AccessToken wxOAuth2AccessToken = wxService.getOAuth2Service().getAccessToken(code);
            final WxOAuth2UserInfo wxOAuth2UserInfo = wxService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, "zh_CN");
            RedisUtil.set("qrCode:" + key, (wxOAuth2UserInfo.getOpenid() + ":" + wxOAuth2UserInfo.getNickname()));
            QrCodeController.log.info("【微信网页授权】wxMpUser={}", wxOAuth2UserInfo);
        }
        catch (WxErrorException e) {
            QrCodeController.log.info("【微信网页授权】{}", (Throwable)e);
            throw new Exception(e.getError().getErrorMsg());
        }
    }
    
    @ResponseBody
    @GetMapping({ "/getOpenId" })
    public ResponseEntity userInfo(final HttpServletRequest request, @RequestParam("key") final String key) {
        final String openId = (String)RedisUtil.get("qrCode:" + key);
        if (openId != null) {
            final String[] str = openId.split(":");
            final JSONObject json = new JSONObject();
            json.put("openId", str[0]);
            json.put("nickName", str[1]);
            return new ResponseEntity(json, HttpStatus.OK);
        }
        return new ResponseEntity(HttpStatus.OK);
    }
    
    public QrCodeController(final RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }
    
    static {
        log = LoggerFactory.getLogger((Class)QrCodeController.class);
    }
}
